package com.xiangmo.travel.Controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.qiniu.storage.model.DefaultPutRet;
import com.xiangmo.travel.Annotation.TokenRequired;
import com.xiangmo.travel.Dto.ResultData;
import com.xiangmo.travel.Enums.CodeAndMsg;
import com.xiangmo.travel.Utils.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 七牛云工具类
 * @author linfen
 * @since 2020-04-8
 */
@Slf4j
@RestController
@RequestMapping("/api/qiniu")
public class QiNiuController {

    @Autowired
    private QiniuUtil qiniuUtil;

    /**
     * 七牛云文件上传
     *
     * @param file 文件
     * @return
     */
    @TokenRequired
    @ResponseBody
    @RequestMapping("/upload/images/{url}")
    public ResultData<Map<String, Object>> upload(@PathVariable String url, MultipartFile[] file,
                                                  @RequestHeader("Authorization") String token) {
        if (file.length <= 0) {
            return new ResultData<>(CodeAndMsg.FILE_NULL_ERROR.getCode(), CodeAndMsg.FILE_NULL_ERROR.getMessage(),
                    null, token.substring(7));
        }
        if (file[0].isEmpty()) {
            return new ResultData<>(CodeAndMsg.FILE_NULL_ERROR.getCode(), CodeAndMsg.FILE_NULL_ERROR.getMessage(),
                    null, token.substring(7));
        }
        try {
            System.out.println(file[0].getInputStream());
            BufferedInputStream fileInputStream = new BufferedInputStream(file[0].getInputStream());

            String originalFilename = file[0].getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            String yyyyMMddHHmmss = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;

            Map<String, Object> map = new HashMap<>();
            DefaultPutRet uploadInfo = new DefaultPutRet();
            if(url.equals("attractions")){
                uploadInfo = qiniuUtil.upload(fileInputStream, "images/attractions/" + fileKey);
                map.put("url", "http://hlwj2526.xyz/" + uploadInfo.key);
            }else if(url.equals("icon")){
                uploadInfo = qiniuUtil.upload(fileInputStream, "images/icon/" + fileKey);
                map.put("url", "http://hlwj2526.xyz/" + uploadInfo.key);
            }else if(url.equals("community")){
                uploadInfo = qiniuUtil.upload(fileInputStream, "images/postings/" + fileKey);
                map.put("url", "http://hlwj2526.xyz/" + uploadInfo.key);
            }else if(url.equals("usericon")){
                uploadInfo = qiniuUtil.upload(fileInputStream, "images/usericon/" + fileKey);
                map.put("url", "http://hlwj2526.xyz/" + uploadInfo.key);
            }
//            DefaultPutRet upl/oadInfo = qiniuUtil.upload(fileInputStream, fileKey);

            map.put("fileName", uploadInfo.key);
            map.put("originName", originalFilename);
            map.put("size", file[0].getSize());
            //七牛云文件私有下载地址（看自己七牛云公开还是私有配置）
//            map.put("url", "/linfen/qiniu/file/" + uploadInfo.key);//七牛云公开下载地址
            log.info("文件：" + JSON.toJSONString(map));
            return new ResultData<>(CodeAndMsg.SUCCESS.getCode(), CodeAndMsg.SUCCESS.getMessage(),
                    map, token.substring(7));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(CodeAndMsg.FILE_ERROR.getCode(), CodeAndMsg.FILE_ERROR.getMessage(),
                    null, token.substring(7));
        }
    }

    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @RequestMapping("/private/file/images/attractions/{filename}")
    public void privateDownloadAttractions(@PathVariable("filename") String filename, HttpServletResponse response,
                                           @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return;
        }
        try {
            String privateFile = qiniuUtil.getPrivateFile("images/attractions/"+filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @RequestMapping("/private/file/images/icon/{filename}")
    public void privateDownloadIcon(@PathVariable("filename") String filename, HttpServletResponse response,
                                    @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return;
        }
        try {
            String privateFile = qiniuUtil.getPrivateFile("images/icon/"+filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @RequestMapping("/private/file/images/community/{filename}")
    public void privateDownloadCommunity(@PathVariable("filename") String filename, HttpServletResponse response,
                                         @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return;
        }
        try {
            String privateFile = qiniuUtil.getPrivateFile("images/postings/"+filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @RequestMapping("/private/file/images/usericon/{filename}")
    public void privateDownloadUserIcon(@PathVariable("filename") String filename, HttpServletResponse response,
                                        @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return;
        }
        try {
            String privateFile = qiniuUtil.getPrivateFile("images/usericon/"+filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 七牛云文件下载
     *
     * @param filename 文件名
     * @return
     */
    @RequestMapping("/file/{filename}")
    public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return;
        }

        try {
            String privateFile = qiniuUtil.getFile(filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛云删除文件
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @PreAuthorize("hasAuthority('sys:qiniu:delete')")
    @DeleteMapping("/delete/file/images/attractions/{filename}")
    public ResultData<Integer> deleteFileAttraction(@PathVariable("filename") String filename, HttpServletResponse response,
                                          @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return new ResultData<>(CodeAndMsg.FILE_NO_ERROR.getCode(), CodeAndMsg.FILE_NO_ERROR.getMessage(),
                    null, token.substring(7));
        }

        try {
            boolean result = qiniuUtil.delete("images/attractions/" + filename);
            if (result)
                return new ResultData<>(CodeAndMsg.DELETE_SUCCESS.getCode(), CodeAndMsg.DELETE_SUCCESS.getMessage(),
                    null, token.substring(7));
            else
                return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                        null, token.substring(7));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                    null, token.substring(7));
        }
    }

    /**
     * 七牛云删除文件
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @PreAuthorize("hasAuthority('sys:qiniu:delete')")
    @DeleteMapping("/delete/file/images/icon/{filename}")
    public ResultData<Integer> deleteFileIcon(@PathVariable("filename") String filename, HttpServletResponse response,
                                          @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return new ResultData<>(CodeAndMsg.FILE_NO_ERROR.getCode(), CodeAndMsg.FILE_NO_ERROR.getMessage(),
                    null, token.substring(7));
        }

        try {
            boolean result = qiniuUtil.delete("images/icon/" + filename);
            if (result)
                return new ResultData<>(CodeAndMsg.DELETE_SUCCESS.getCode(), CodeAndMsg.DELETE_SUCCESS.getMessage(),
                        null, token.substring(7));
            else
                return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                        null, token.substring(7));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                    null, token.substring(7));
        }
    }
    /**
     * 七牛云删除文件
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @PreAuthorize("hasAuthority('sys:qiniu:delete')")
    @DeleteMapping("/delete/file/images/community/{filename}")
    public ResultData<Integer> deleteFileCommunity(@PathVariable("filename") String filename, HttpServletResponse response,
                                          @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return new ResultData<>(CodeAndMsg.FILE_NO_ERROR.getCode(), CodeAndMsg.FILE_NO_ERROR.getMessage(),
                    null, token.substring(7));
        }

        try {
            boolean result = qiniuUtil.delete("images/postings/" + filename);
            if (result)
                return new ResultData<>(CodeAndMsg.DELETE_SUCCESS.getCode(), CodeAndMsg.DELETE_SUCCESS.getMessage(),
                        null, token.substring(7));
            else
                return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                        null, token.substring(7));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                    null, token.substring(7));
        }
    }
    /**
     * 七牛云删除文件
     *
     * @param filename 文件名
     * @return
     */
    @TokenRequired
    @PreAuthorize("hasAuthority('sys:qiniu:delete')")
    @DeleteMapping("/delete/file/images/usericon/{filename}")
    public ResultData<Integer> deleteFileUserIcon(@PathVariable("filename") String filename, HttpServletResponse response,
                                          @RequestHeader("Authorization") String token) {
        if (filename.isEmpty()) {
            return new ResultData<>(CodeAndMsg.FILE_NO_ERROR.getCode(), CodeAndMsg.FILE_NO_ERROR.getMessage(),
                    null, token.substring(7));
        }

        try {
            boolean result = qiniuUtil.delete("images/usericon/" + filename);
            if (result)
                return new ResultData<>(CodeAndMsg.DELETE_SUCCESS.getCode(), CodeAndMsg.DELETE_SUCCESS.getMessage(),
                        null, token.substring(7));
            else
                return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                        null, token.substring(7));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(CodeAndMsg.DELETE_ERROR.getCode(), CodeAndMsg.DELETE_ERROR.getMessage(),
                    null, token.substring(7));
        }
    }
}